#include "Rp2Image.h"
#include "Rp2ImageVersion.h"
#include "Rp2Tga.h"

using namespace Rp2;

//---------------------------------------------------------------------------------------------------
Image* Image::LoadImageWMIF(const char* rkDecorated, const std::string& rkFilename)
{
	// load .wmif image file
	char* acBuffer;
	int iSize;
	bool bLoaded = System::Load(rkDecorated,acBuffer,iSize);
	if (!bLoaded)
	{
		// file does not exist
		System::MsgBoxPrintf(TC("Image::Load"), TC("Image : %s does not exist"), rkFilename);
		return 0;
	}

	if (iSize < ImageVersion::LENGTH)
	{
		// file not large enough to store version string
		delete[] acBuffer;
		return 0;
	}

	// read the file version
	ImageVersion kVersion(acBuffer);
	if (!kVersion.IsValid())
	{
		delete[] acBuffer;
		return 0;
	}

	char* pcCurrent = acBuffer + ImageVersion::LENGTH;

	// read the image format and dimensions
	int iFormat, iDimension, aiBound[3];
	pcCurrent += System::Read4le(pcCurrent,1,&iFormat);
	if (kVersion >= ImageVersion(3,1))
	{
		pcCurrent += System::Read4le(pcCurrent,1,&iDimension);
	}
	else
	{
		iDimension = 2;
	}
	pcCurrent += System::Read4le(pcCurrent,1,&aiBound[0]);
	pcCurrent += System::Read4le(pcCurrent,1,&aiBound[1]);
	if (kVersion >= ImageVersion(3,1))
	{
		pcCurrent += System::Read4le(pcCurrent,1,&aiBound[2]);
	}
	else
	{
		aiBound[2] = 1;
	}

	FormatMode eFormat = (FormatMode)iFormat;
	int iQuantity = aiBound[0]*aiBound[1]*aiBound[2];

	// read the image data
	int iDataSize = ms_aiBytesPerPixel[eFormat]*iQuantity;
	if (eFormat == Image::IT_CUBE_RGB888
	||  eFormat == Image::IT_CUBE_RGBA8888)
	{
		iDataSize *= 6;
	}
	unsigned char* aucData = new unsigned char[iDataSize];
	System::Read1(pcCurrent,iDataSize,aucData);

	Image* pkImage = 0;
	switch (iDimension)
	{
	case 1:
		pkImage = new Image(eFormat,aiBound[0],aucData,
			rkFilename.c_str());
		break;
	case 2:
		pkImage = new Image(eFormat,aiBound[0],aiBound[1],aucData,
			rkFilename.c_str());
		break;
	case 3:
		pkImage = new Image(eFormat,aiBound[0],aiBound[1],aiBound[2],
			aucData,rkFilename.c_str());
		break;
	default:
		assert(false);
	}

	delete[] acBuffer;
	return pkImage;
}
//---------------------------------------------------------------------------------------------------
Image* Image::LoadImageTGA(const char* rkDecorated, const std::string& rkFilename)
{
	//load .tga image file
	char* acBuffer;
	int iSize;
	bool bLoaded = System::Load(rkDecorated, acBuffer,iSize);
	Image* pkImage = Tga::LoadTGA((const unsigned char*)acBuffer, rkFilename);

	delete[] acBuffer;
	return pkImage;
}
//---------------------------------------------------------------------------------------------------